package org.ascollada.io
{
	import flash.display.Bitmap;
	import flash.errors.IOError;
	import flash.net.URLRequest;
	
	import org.ascollada.core.DaeImage;
	import org.ascollada.events.DaeParseEvent;
	import org.ascollada.utils.DaeLogger;
	import org.libspark.thread.Thread;
	import org.libspark.thread.threads.display.LoaderThread;
	import org.libspark.thread.utils.EventDispatcherThread;
	
	/**
	 * @author Tim Knip / floorplanner.com
	 */ 
	public class DaeImageLoaderThread extends EventDispatcherThread
	{
		public var images :Object;
		
		private var _images :Array;
		private var _currentImage :DaeImage;
		private var _totalImages :int;
		private var _loader :LoaderThread;
		private var _baseUrl :String;
		
		/**
		 * 
		 */ 
		public function DaeImageLoaderThread(baseUrl:String="")
		{
			super();
			
			this.images = new Object();
			
			_baseUrl = baseUrl;	
			_images = new Array();
		}
		
		/**
		 * 
		 */ 
		public function addImage(image:DaeImage):void
		{
			var parts :Array;
			var base :Array;
			var i :int;
			
			if(image.init_from.charAt(0) == "." && image.init_from.charAt(1) == "/")
			{
				image.init_from = _baseUrl + image.init_from.substr(1);
			}
			else if(image.init_from.charAt(0) == "/")
			{
				image.init_from = image.init_from.substr(1);
			}
			else if(image.init_from.charAt(0) == "." && image.init_from.charAt(1) == ".")
			{
				base = _baseUrl.split("/");
				parts = image.init_from.split("/");
				image.init_from = parts.pop() as String;
				var tmp :Array = new Array();
				
				for(i = 0; i < parts.length; i++)
				{
					if(parts[i] == "..")
					{
						base.pop();
					}
					else
					{
						tmp.push(parts[i]);
					}
				}
				if(base.length)
				{
					tmp.unshift(base.join("/"));
				}
				image.init_from = tmp.join("/") + "/" + image.init_from;
			}
			else if(image.init_from.indexOf("http://") != -1 || image.init_from.indexOf("file:///") != -1)
			{
				parts = image.init_from.split("/");
				image.init_from = _baseUrl + "/" + parts.pop() as String;
			}
			else
			{
				image.init_from = _baseUrl + "/" + image.init_from;
			}
			
			DaeLogger.log("[DaeImageLoaderThread] Adding image: " + image.id + " " + image.init_from);
			
			_images.push(image);
		}
		
		/**
		 * 
		 */ 
		protected override function run():void
		{
			if(!_images || !_images.length)
			{
				_totalImages = 0;
				return;
			}
			
			_totalImages = _images.length;
			_currentImage = _images.shift() as DaeImage;
			
			_loader = new LoaderThread(new URLRequest(_currentImage.init_from));
			_loader.start();
			_loader.join();
			
			next(executeComplete);

			error(IOError, errorHandler);
			error(SecurityError, errorHandler);
		}
		
		/**
		 * 
		 */ 
		private function executeComplete():void
		{
			DaeLogger.log("[DaeImageLoaderThread] Loaded image : " + _currentImage.id + " " + _currentImage.init_from );
			
			if(_loader.loader && _loader.loader.content is Bitmap)
			{
				_currentImage.data = Bitmap(_loader.loader.content).bitmapData;
			}
			
			if(_images.length)
			{
				run();
			}
			else
			{
				DaeLogger.log("[DaeImageLoaderThread] Thread completed.");
				dispatchEvent(new DaeParseEvent(DaeParseEvent.IMAGES_COMPLETE));
			}
		}
		
		/**
		 * 
		 */ 
		private function errorHandler(e:IOError, t:Thread):void
		{
			DaeLogger.log("[DaeImageLoaderThread] Image failed to load id:" + _currentImage.id + " url:" + _currentImage.init_from);

			if(_images.length)
			{
				run();
			}
			else
			{
				DaeLogger.log("[DaeImageLoaderThread] Thread completed.");
				dispatchEvent(new DaeParseEvent(DaeParseEvent.IMAGES_COMPLETE));
				next(null);
			}
		}
	}
}